<?php

class Dbase {
	var $CI;

	function __construct() {
		$this->CI = & get_instance();
	}

	/**
	 * Verifica duplicate
	 * $aData - array similar for inserting with active records (column=>value)
	 * $aKey - keys for identification
	 * $exclude -  exclude records Ex. array ("doc_id"=>3, "name"=>"t1"...)
	 *      */
	function verifyDuplicate($table, $aData, $criteria, $exclude = array()) {

		if (($table == "") || (! is_array($aData)) || (! is_array($exclude))) {
			die ("Smarty..verifyDuplicate failed 1");
		}

		if (is_array($criteria)) {
			foreach ($criteria as $sValue) {
				if (! isset($aData[$sValue])) {
					die ("Smarty..verifyDuplicate failed 2");
				}
				$this->CI->db->where("$sValue", $aData[$sValue]);
			}
		} else {
			if (! isset($aData[$criteria])) {
				die ("Smarty..verifyDuplicate failed 3");
			}
			$this->CI->db->where("$criteria", $aData[$criteria]);
		}

		//exclude itself from search
		foreach ($exclude as $sColumn => $sValue) {
			$this->CI->db->where("$sColumn !=", $sValue);
		}

		$aQuery = $this->CI->db->get($table);

		if ($aQuery->num_rows() >= 1) {
			return TRUE;
		}

		return FALSE;
	}

	/**
	 * Functie de cautare
	 * @param  $aFields
	 * @param null $sQuery
	 * @return null|string
	 */
	function getQuickWhere($aFields, $sQuery = NULL) {

		$where = " (";
		if (is_null($sQuery)) {
			return $sQuery;
		}

		if ($sQuery && is_array($aFields) && sizeof($aFields)) {
			$a = array();
			foreach ($aFields as $f) {
				$a[] = "$f regexp '$sQuery'";
			}
			$where .= implode(" or ", $this->CI->db->escape($a)).")";
		}

		return $where;
	}


}

?>
